<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小同住人员物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\property\repair;

use think\App;
use app\controller\property\Base;
use app\validate\repair\RepairOrderValidate;
use app\common\repositories\room\RoomBasicRepository;
use app\common\repositories\repair\RepairCateRepository;
use app\common\repositories\repair\RepairOrderRepository;
use app\common\repositories\repair\RepairLogRepository;
use app\common\repositories\property\users\PropertyUsersRepository;
use app\common\repositories\property\basic\PropertyBasicRepository;

class RepairOrder extends Base
{
    protected $repository;

    public function __construct(App $app, RepairOrderRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
        if (!$this->request->isAjax()) {
            $this->assign([
                'addAuth' => property_auth('propertyRepairOrderAdd'),
                'editAuth' => property_auth('propertyRepairOrderEdit'),
                'delAuth' => property_auth('propertyRepairOrderDel'),
                'cancelAuth' => property_auth('propertyRepairOrderCancel'),
                'allotAuth' => property_auth('propertyRepairOrderAllot'),
                'handleAuth' => property_auth('propertyRepairOrderHandle'),
                'detailAuth' => property_auth('propertyRepairOrderDetail')
            ]);
        }
    }


    protected function commonParams()
    {
        /** @var RepairCateRepository $repairCateRepository */
        $repairCateRepository = app()->make(RepairCateRepository::class);
        $cateNameData = $repairCateRepository->getCascaderData($this->request->propertyId);

        $this->assign([
            'cateNameData' => $cateNameData,
        ]);
    }

    public function list()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param([
                'cates_id' => '',
                'cate_id' => '',
                'user_id' => '',
                'keywords' => ''
            ]);
            [$page, $limit] = $this->getPage();
            $data = $this->repository->getpropertyList($param, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $data['list'], 'count' => $data['count']]);
        }

        $this->commonParams();
        return $this->fetch('repair/order/list');
    }

    /**
     * 待处理报修列表
     */
    public function awaitList()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param([
                'cates_id' => '',
                'cate_id' => '',
                'keywords' => ''
            ]);
            $param['status'] = 1;
            [$page, $limit] = $this->getPage();
            $data = $this->repository->getpropertyList($param, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $data['list'], 'count' => $data['count']]);
        }
        $this->commonParams();
        return $this->fetch('repair/order/await/list');
    }

    /**
     * 处理中报修列表
     */
    public function inProcessList()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param([
                'cates_id' => '',
                'cate_id' => '',
                'keywords' => ''
            ]);
            $param['status'] = 2;
            [$page, $limit] = $this->getPage();
            $data = $this->repository->getpropertyList($param, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $data['list'], 'count' => $data['count']]);
        }
        $this->commonParams();
        return $this->fetch('repair/order/inProcess/list');
    }

    /**
     * 己处理报修列表
     */
    public function finishList()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param([
                'cates_id' => '',
                'cate_id' => '',
                'keywords' => ''
            ]);
            $param['status'] = 3;
            [$page, $limit] = $this->getPage();
            $data = $this->repository->getpropertyList($param, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $data['list'], 'count' => $data['count']]);
        }
        $this->commonParams();
        return $this->fetch('repair/order/finish/list');
    }

    /**
     * 己取消报修列表
     */
    public function cancelList()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param([
                'cates_id' => '',
                'cate_id' => '',
                'keywords' => ''
            ]);
            $param['status'] = 4;
            [$page, $limit] = $this->getPage();
            $data = $this->repository->getpropertyList($param, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $data['list'], 'count' => $data['count']]);
        }
        $this->commonParams();
        return $this->fetch('repair/order/cancel/list');
    }


    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'cate_id' => '',
                'room_id' => '',
                'content' => '',
                'picture' => '',
                'repair_no' => '',
                'contact_name' => '',
                'contact_mobile' => '',
                'hope_date' => '',
                'hope_time' => '',
            ]);
            $param['status'] = 1;
            validate(RepairOrderValidate::class)->scene('add')->check($param);
            if ($this->repository->fieldExists('repair_no', $param['repair_no'])) {
                return $this->error($param['repair_no'] . '工单编号已存在');
            }
            try {
                $res = $this->repository->addInfo($this->request->propertyId, $param, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('添加维修工单信息失败', $e);
                return $this->error('网络错误');
            }
        } else {
            $this->commonParams();
            /** @var RoomBasicRepository $roomRepository */
            $roomRepository = app()->make(RoomBasicRepository::class);
            $roomData = $roomRepository->getSearch([])
                ->where('status', 1)
                ->where('property_id', $this->request->propertyId)
                ->append(['full_room_name'])
                ->select()->toArray();
            return $this->fetch('repair/order/add', [
                'roomData' => $roomData,
                'repairNo' => 'M' . date('ymd') . get_rand_member(4) . 'H' . date('His')
            ]);
        }
    }

    /**
     * 编辑
     * @return array|string|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->get($id);
        if (!$info) {
            return $this->error('信息获取失败');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'content' => '',
                'picture' => '',
                'contact_name' => '',
                'contact_mobile' => '',
                'hope_date' => '',
                'hope_time' => '',
            ]);
            validate(RepairOrderValidate::class)->scene('edit')->check($param);
            try {
                $res = $this->repository->editInfo($info, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->success('数据无变化');
                }
            } catch (\Exception $e) {
                exception_log('编辑维修工单信息失败', $e);
                return $this->success('修改失败');
            }
        } else {
            $this->commonParams();
            return $this->fetch('repair/order/edit', [
                'info' => $info,
            ]);
        }
    }

    public function detail()
    {
        $repairId = (int)$this->request->param('id');
        if ($repairId <= 0) {
            return $this->error('参数错误');
        }
        $info = $this->repository->get($repairId);
        if ($info['id'] <= 0) {
            return $this->error('工单信息不存在');
        }
        $this->commonParams();
        return $this->fetch('repair/order/detail', [
            'info' => $info,
        ]);
    }


    public function cancel()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'id' => '',
                'cancel_remark' => '',
            ]);
            $ids = array_filter(explode(',', $param['id']));
            $num = 0;
            foreach ($ids as $v) {
                $info = $this->repository->get($v);
                if (isset($info) && $info['id'] > 0 && $info['status'] <= 2) {
                    $res = $this->repository->cancellnfo($info, $param, $this->request->userId);
                    if ($res) {
                        $num++;
                    }
                }
            }
            if ($num) {
                return $this->success('成功取消' . $num . '个任务');
            } else {
                return $this->error('批量取消任务失败');
            }
        } else {
            $id = $this->request->param('id');
            $id = array_filter(explode(',', $id));
            $repairData = $this->repository->getSearch([])
                ->where('id', 'in', $id)
                ->where('status', 'in', '1,2')
                ->field('id,contact_name,contact_mobile,content,hope_date,hope_time')
                ->select()->toArray();
            $this->assign([
                'repairData' => $repairData,
            ]);
            return $this->fetch('repair/order/cancel');
        }

    }

    public function handle()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'id' => '',
                'remark' => '',
                'picture' => '',
                'share_uid' => '',
            ]);
            $ids = array_filter(explode(',', $param['id']));
            $num = 0;
            foreach ($ids as $v) {
                $info = $this->repository->get($v);
                if (isset($info) && $info['id'] > 0 && $info['status'] == 2) {
                    $res = $this->repository->handlelnfo($info, $param, $this->request->userId);
                    if ($res) {
                        $num++;
                    }
                }
            }
            if ($num) {
                return $this->success('成功处理' . $num . '个任务');
            } else {
                return $this->error('批量处理工单失败');
            }
        } else {
            $id = $this->request->param('id');
            $id = array_filter(explode(',', $id));
            $list = $this->repository->getSearch([])
                ->where('id', 'in', $id)
                ->where('status', '2')
                ->field('id,contact_name,contact_mobile,content,hope_date,hope_time')
                ->select()->toArray();
            $repairData = $list;
            /** @var PropertyUsersRepository $propertyUsersRepository */
            $propertyUsersRepository = app()->make(PropertyUsersRepository::class);
            $userList = $propertyUsersRepository->getSearch(['is_show' => 1])
                ->with([
                    'userInfo' => function ($query) {
                        $query->bind(['username' => 'username', 'mobile' => 'mobile']);
                    }
                ])
                ->select();
            $this->assign([
                'repairData' => $repairData,
                'userList' => $userList
            ]);
            return $this->fetch('repair/order/handle');
        }
    }


    public function del()
    {
        $ids = (array)$this->request->param('ids');
        try {
            $data = $this->repository->batchDelete($ids, $this->request->userId);
            if ($data) {
                return $this->success('删除维修工单信息成功');
            } else {
                return $this->error('删除维修工单信息失败');
            }
        } catch (\Exception $e) {
            exception_log('删除维修工单信息失败', $e);
            return $this->error('网络失败');
        }
    }


    public function logs(RepairLogRepository $repository)
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'repair_id' => '',
                'user_id' => '',
                'keywords' => '',
                'add_time' => '',
            ]);
            [$page, $limit] = $this->getPage();
            $res = $repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
    }


    public function allot()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'id' => '',
                'remark' => '',
                'share_uid' => '',
            ]);
            $ids = array_filter(explode(',', $param['id']));
            $num = 0;
            foreach ($ids as $v) {
                $info = $this->repository->get($v);
                if (isset($info) && $info['id'] > 0 && $info['status'] == 1) {
                    $res = $this->repository->allotInfo($info, $param, $this->request->userId);
                    if ($res) {
                        $num++;
                    }
                }
            }
            if ($num) {
                return $this->success('成功分配' . $num . '个任务');
            } else {
                return $this->error('批量分配任务失败');
            }
        } else {
            $id = $this->request->param('id');
            $id = array_filter(explode(',', $id));
            $list = $this->repository->getSearch([])
                ->where('status', 1)
                ->where('id', 'in', $id)
                ->field('id,contact_name,contact_mobile,content,hope_date,hope_time')
                ->select()->toArray();
            $repairData = $list;
            /** @var PropertyUsersRepository $propertyUsersRepository */
            $propertyUsersRepository = app()->make(PropertyUsersRepository::class);
            $userList = $propertyUsersRepository->getSearch(['is_show' => 1])
                ->with([
                    'userInfo' => function ($query) {
                        $query->bind(['username' => 'username', 'mobile' => 'mobile']);
                    }
                ])
                ->select();
            $this->assign([
                'repairData' => $repairData,
                'userList' => $userList
            ]);
            return $this->fetch('repair/order/allot');
        }
    }

}